﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YougeBookmark.Models;
using YougeBookmark.Utilities;

namespace YougeBookmark.Data
{
    public class TagRepository
    {
        private readonly DatabaseContext _context;
        private readonly BookmarkTagRepository _bookmarkTagRepo; // 新增字段
        private readonly Logger _logger;

        public async Task<List<Tag>> GetByNamesAsync(IEnumerable<string> names)
        {
            var normalizedNames = names.Select(n => n.Trim().ToLower());
            return await _context.Tags
                .Where(t => normalizedNames.Contains(t.Name.ToLower()))
                .ToListAsync();
        }

        public async Task<Tag> CreateAsync(string name)
        {
            return await AddAsync(name); // 复用已有Add逻辑
        }

        public async Task DeleteAssociationAsync(int bookmarkId, int tagId)
        {
            await _bookmarkTagRepo.DeleteAsync(bookmarkId, tagId);
        }

        // TagRepository.cs 添加以下方法
        public IQueryable<Tag> GetAll()
        {
            return _context.Tags.AsQueryable();
        }

        public IDbContextTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel = System.Data.IsolationLevel.ReadCommitted)
        {
            return _context.Database.BeginTransaction(isolationLevel);
        }

        public TagRepository(DatabaseContext context, BookmarkTagRepository bookmarkTagRepo, Logger logger)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _bookmarkTagRepo = bookmarkTagRepo ?? throw new ArgumentNullException(nameof(bookmarkTagRepo));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 创建新标签（自动设置创建时间）
        /// </summary>
        public async Task<Tag> AddAsync(string tagName)
        {
            try
            {
                if (await CheckNameExistsAsync(tagName))
                {
                    _logger.Warn($"标签名称已存在: {tagName}");
                    return null;
                }

                var entity = new Tag
                {
                    Name = tagName.Trim(),
                    CreatedAt = DateTime.UtcNow
                };

                _context.Tags.Add(entity);
                await _context.SaveChangesAsync();
                return entity;
            }
            catch (Exception ex)
            {
                _logger.Error($"创建标签失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 删除标签及关联关系（级联删除）
        /// </summary>
        public async Task<bool> DeleteAsync(int tagId)
        {
            //try
            //{
            //    var entity = await _context.Tags
            //        .Include(t => t.BookmarkTags)
            //        .FirstOrDefaultAsync(t => t.Id == tagId);

            //    if (entity == null) return false;

            //    _context.Tags.Remove(entity);
            //    await _context.SaveChangesAsync();
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    _logger.Error($"删除标签失败: {ex.Message}", ex);
            //    throw;
            //}
            try
            {
                // 直接通过ID删除（不再包含Include）
                var entity = await _context.Tags.FindAsync(tagId);
                if (entity == null) return false;

                _context.Tags.Remove(entity);
                await _context.SaveChangesAsync();
                _logger.Info($"成功删除标签: {entity.Name}(ID:{tagId})");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error($"删除标签失败(ID:{tagId}): {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 更新标签名称（自动更新修改时间）
        /// </summary>
        public async Task<Tag> UpdateAsync(int tagId, string newName)
        {
            try
            {
                var entity = await _context.Tags.FindAsync(tagId);
                if (entity == null) return null;

                if (await CheckNameExistsAsync(newName, tagId))
                {
                    _logger.Warn($"新标签名称已存在: {newName}");
                    return null;
                }

                entity.Name = newName.Trim();
                entity.ModifiedAt = DateTime.UtcNow;
                _context.Tags.Update(entity);
                await _context.SaveChangesAsync();
                return entity;
            }
            catch (Exception ex)
            {
                _logger.Error($"更新标签失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取所有标签（按创建时间倒序）
        /// </summary>
        public async Task<List<Tag>> GetAllAsync()
        {
            return await _context.Tags
                .OrderByDescending(t => t.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 分页查询标签列表
        /// </summary>
        public async Task<(List<Tag> Items, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize)
        {
            try
            {
                var query = _context.Tags.AsNoTracking();
                var total = await query.CountAsync();

                var items = await query
                    .OrderBy(t => t.Name)
                    .Skip(pageIndex * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                return (items, total);
            }
            catch (Exception ex)
            {
                _logger.Error($"分页查询失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 检查标签名称是否存在（排除自身）
        /// </summary>
        public async Task<bool> CheckNameExistsAsync(string name, int? excludeId = null)
        {
            var query = _context.Tags.Where(t => t.Name == name.Trim());
            if (excludeId.HasValue)
                query = query.Where(t => t.Id != excludeId.Value);

            return await query.AnyAsync();
        }

        /// <summary>
        /// 根据名称精确查找标签
        /// </summary>
        public async Task<Tag> GetByNameAsync(string name)
        {
            return await _context.Tags
                .FirstOrDefaultAsync(t => t.Name == name.Trim());
        }

        /// <summary>
        /// 根据ID获取标签实体
        /// </summary>
        public async Task<Tag> GetByIdAsync(int tagId)
        {
            return await _context.Tags.FindAsync(tagId);
        }
    }
}